import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('admin_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const { data } = response
    if (data.code === 200) {
      return data
    } else {
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }
  },
  async error => {
    if (error.response) {
      const { status, data } = error.response
      if (status === 401) {
        // Token过期，跳转到登录页
        localStorage.removeItem('admin_token')
        window.location.href = '/login'
      } else if (status === 404 || status === 500) {
        // 接口不存在或服务器错误，尝试使用模拟数据
        console.warn('接口错误，尝试使用模拟数据:', error.config.url)
        try {
          const { mockAPI } = await import('./mock')

          // 根据URL匹配对应的模拟接口
          if (error.config.url.includes('/adminLogin')) {
            return mockAPI.adminLogin(JSON.parse(error.config.data))
          } else if (error.config.url.includes('/admin/users')) {
            if (error.config.method === 'get') {
              return mockAPI.getUserList(error.config.params)
            } else if (error.config.url.includes('/stats')) {
              return mockAPI.getUserStats()
            }
          } else if (error.config.url.includes('/banners')) {
            if (error.config.method === 'get') {
              if (/\/banners\/\d+/.test(error.config.url)) {
                const id = error.config.url.match(/\/banners\/(\d+)/)[1]
                return mockAPI.getCarouselDetail(id)
              } else if (error.config.url.includes('/active')) {
                return mockAPI.getActiveCarouselList()
              } else {
                return mockAPI.getCarouselList(error.config.params)
              }
            } else if (error.config.method === 'post') {
              return mockAPI.createCarousel(JSON.parse(error.config.data))
            } else if (error.config.method === 'put') {
              if (error.config.url.includes('/sort')) {
                return mockAPI.updateCarouselSort(JSON.parse(error.config.data))
              } else if (error.config.url.includes('/enable')) {
                const id = error.config.url.match(/\/banners\/(\d+)\/enable/)[1]
                return mockAPI.updateCarouselStatus(id, 1)
              } else if (error.config.url.includes('/disable')) {
                const id = error.config.url.match(/\/banners\/(\d+)\/disable/)[1]
                return mockAPI.updateCarouselStatus(id, 0)
              } else {
                const id = error.config.url.match(/\/banners\/(\d+)/)[1]
                const data = JSON.parse(error.config.data)
                return mockAPI.updateCarousel(id, data)
              }
            } else if (error.config.method === 'delete') {
              const id = error.config.url.match(/\/banners\/(\d+)/)[1]
              return mockAPI.deleteCarousel(id)
            }
          } else if (error.config.url.includes('/products')) {
            if (error.config.method === 'get') {
              if (error.config.url.includes('/categories')) {
                return mockAPI.getProductCategories()
              } else if (error.config.url.includes('/stats')) {
                return mockAPI.getProductStats()
              } else if (/\/products\/\d+/.test(error.config.url)) {
                const id = error.config.url.match(/\/products\/(\d+)/)[1]
                return mockAPI.getProductDetail(id)
              } else {
                return mockAPI.getProductList(error.config.params)
              }
            } else if (error.config.method === 'post') {
              return mockAPI.createProduct(JSON.parse(error.config.data))
            } else if (error.config.method === 'put') {
              const id = error.config.url.match(/\/products\/(\d+)/)[1]
              const data = JSON.parse(error.config.data)
              return mockAPI.updateProduct(id, data)
            } else if (error.config.method === 'delete') {
              const id = error.config.url.match(/\/products\/(\d+)/)[1]
              return mockAPI.deleteProduct(id)
            }
          }

          // 如果没有匹配的模拟接口，显示错误
          ElMessage.warning(`接口 ${error.config.url} 暂未实现，显示演示数据`)
          return Promise.reject(error)
        } catch (mockError) {
          ElMessage.error(data?.message || `请求失败 (${status})`)
          return Promise.reject(error)
        }
      } else {
        ElMessage.error(data?.message || `请求失败 (${status})`)
      }
    } else {
      ElMessage.error('网络错误')
    }
    return Promise.reject(error)
  }
)

export default request